<template>
  <div class="app-container">
    <div v-if="$route.query.type" class="back-title">
      <i class="el-icon-arrow-left" @click="$router.go(-1)">返回</i>
    </div>
    <div v-if="hiddenForm" class="tabs-header">
      <hk-form
        ref="hkFormRef"
        :form-labels="formObj.formLabels"
        :data="formData"
        :rules="formObj.formRules"
        label-position="left"
        size="small"
        :dict-list="formObj.dictList"
        :btn-hidden="true"
      >
        <template #filter-codeNumFormat>
          <el-row>
            <el-col :span="7">
              <el-input
                v-model="textFormat"
                :disabled="disabled"
                :clearable="true"
                place-holder="请输入"
                maxlength="100"
              />
            </el-col>
            <el-col :span="7" style="margin: 0">
              <el-select v-model="timeFormat" :disabled="disabled" placeholder="请选择">
                <el-option
                  v-for="item in timeFormatList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="7">
              <el-select v-model="numFormat" :disabled="disabled" placeholder="请选择">
                <el-option
                  v-for="item in numFormatList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-col>
          </el-row>
        </template>
        <template v-if="$route.query.type !== 'update'" #filter-enabled>
          <el-checkbox v-model="statusChecked" :disabled="disabled">发布并启用</el-checkbox>
        </template>
        <template #filter-cancellation>
          <el-checkbox v-model="cancellation" :disabled="disabled">允许撤销</el-checkbox>
        </template>
      </hk-form>
      <div v-if="!disabled" style="min-width: 200px; margin-top: 10px">
        <el-button type="primary" @click="submitProcess">保存</el-button>
        <el-button
          style="margin-left: 10px"
          @click="$router.go(-1)"
        >取消</el-button>
      </div>
    </div>
    <vue-bpmn ref="bpmn" class="bpmn" />
  </div>
</template>

<script>
import HkForm from '@/components/HkForm/index.vue'
import VueBpmn from '../components/VueBpmn/index.vue'
import { mapState } from 'vuex'
import { flowCreate, flowUpdate } from '@/api/ticket/processDesign'
import { getProcessDetail } from '@/api/ticket/processDesign'

export default {
  components: {
    HkForm,
    VueBpmn
  },
  beforeRouteLeave(to, from, next) {
    if (to.path.includes('/bpmn/processDesign/list')) {
      to.meta.keepAlive = true
    }
    next()
  },
  data() {
    return {
      formObj: {
        formLabels: [
          //  存在接入系统后改为8,下同
          {
            label: '名称',
            field: 'flowName',
            type: 'input',
            span: 12,
            labelWidth: 50,
            maxlength: 200
          },
          {
            label: '流水号格式',
            field: 'codeNumFormat',
            type: 'slot'
          },
          //  当前不选择接入系统
          // {
          //   label: '服务接入系统',
          //   field: 'fromSystem',
          //   type: 'select',
          //   span: 8,
          //   list: 'typeList'
          // },
          {
            label: '描述',
            field: 'description',
            type: 'textarea',
            span: 8,
            labelWidth: 50,
            maxlength: 200,
            attrs: {
              rows: 2,
              disabled: true
            }
          },
          {
            label: '',
            labelWidth: 1,
            field: 'enabled',
            type: 'slot',
            span: this.$route.query.type === 'update' ? '0' : 3
          },
          {
            label: '',
            labelWidth: 1,
            field: 'cancellation',
            type: 'slot',
            span: 3
          }
        ],
        formRules: {
          flowName: [{ required: true, message: '请填写流程名称', target: ['blur', 'change', 'input'] }]
        },
        dictList: {
          typeList: [
            { label: '未造成失泄密', value: 0 },
            { label: '已造成失泄密', value: 1 }
          ]
        }
      },
      formData: {
        xmlResource: '',
        codeNumFormat: '',
        nodeInfo: {},
        nodeCondition: {}
      },
      //  流水号格式化默认值及字典项
      textFormat: 'order',
      timeFormat: 'yearMonthDay',
      timeFormatList: [
        { value: 'yearMonthDay', label: '年月日' },
        { value: 'yearMonth', label: '年月' },
        { value: 'year', label: '年' }
      ],
      numFormat: '3',
      numFormatList: [
        { value: '3', label: '三位流水号' },
        { value: '4', label: '四位流水号' },
        { value: '5', label: '五位流水号' },
        { value: '6', label: '六位流水号' }
      ],
      //  启用并发布
      statusChecked: true,
      //  是否允许撤销
      cancellation: true,
      //  回显时只读
      disabled: false,
      //  操作类型
      handleType: '',
      //  工单进入页面时隐藏
      hiddenForm: true
    }
  },
  computed: {
    ...mapState({
      // 节点表单信息
      nodeInfo: (state) => state.bpmn.nodeInfo,
      // 节点连线信息
      condition: (state) => state.bpmn.condition
    })
  },
  mounted() {
    this.handleType = this.$route.query.type || 'add'
    this.disabled = this.handleType === 'view'
    if (this.$route.query.flowId) {
      this.hiddenForm = false
    }
    if (this.handleType !== 'add') {
      this.initProcessInfo()
    }
    this.formObj.formLabels.forEach(i => {
      if (i.type === 'textarea') {
        i.attrs.disabled = this.disabled
      } else {
        i.disabled = this.disabled
        if (i.field === 'flowName') {
          i.disabled = this.handleType === 'update' || this.handleType === 'view'
        }
      }
    })
  },
  methods: {
    /** 回显数据 */
    initProcessInfo() {
      getProcessDetail(this.$route.query.id).then(res => {
        this.formData = {
          flowName: res.flowName,
          description: res.description
        }
        const codeNumFormat = res.codeNumFormat.split(',')
        this.textFormat = codeNumFormat[0] || 'test'
        this.timeFormat = codeNumFormat[1] || 'yearMonthDay'
        this.numFormat = codeNumFormat[2] || '3'
        this.statusChecked = res.status === 1 && res.enable === 1
        this.cancellation = res.cancellation === 1
      })
    },
    /** 提交 */
    submitProcess() {
      this.formData.codeNumFormat = `${this.textFormat},${this.timeFormat},${this.numFormat}`
      this.formData.status = this.statusChecked ? 1 : 2
      this.formData.enable = this.statusChecked ? 1 : 0
      this.formData.cancellation = this.cancellation ? 1 : 0
      this.$refs['bpmn'].bpmnModeler.saveXML((err, xml) => {
        // TODO: 获取当前bpmn实例的xml
        if (err) {
          this.$message.error(err)
        } else {
          const cloneNodeInfo = this.nodeInfo
          for (const i in cloneNodeInfo) {
            //  去掉开始节点
            if (i.type === 'bpmn:StartEvent') {
              delete cloneNodeInfo[i]
              continue
            }
            //  删除结束节点
            if (i.includes('Event_')) {
              delete cloneNodeInfo[i]
              continue
            }
            //  删除互斥节点
            if (i.type === 'bpmn:ExclusiveGateway') {
              delete cloneNodeInfo[i]
              continue
            }
            //  删除节点的label节点
            if (i.includes('_label')) {
              delete cloneNodeInfo[i]
              continue
            }
            //  节点信息重新设置删除多余参数
            cloneNodeInfo[i].nodeType = cloneNodeInfo.type
            //  先别删,删除以后第二次点击保存无法获取type
            // delete this.nodeInfo[i].id
            // delete this.nodeInfo[i].type

            cloneNodeInfo[i].noticeList && cloneNodeInfo[i].noticeList.forEach(j => {
              j.conditions = [{
                'variable': j.conditionsLabel,
                'conditionOpt': j.conditionsOption,
                'conditionOptValue': j.conditionsValue
              }]
            })
          }
          this.$refs.hkFormRef.handleFormSubmit('formLabels').then((valid) => {
            if (Object.keys(this.nodeInfo).length === 0) {
              this.$message.error('请添加节点')
              return
            }
            let _flag = false
            const _errorNodes = []
            for (const i in this.nodeInfo) {
              if (!this.nodeInfo[i].formValidFlag) {
                _errorNodes.push(i)
                _flag = true
              }
            }
            if (_flag) {
              console.log(cloneNodeInfo, '\n >>> 所有节点信息')
              console.log(_errorNodes, '\n >>> 报错节点信息')
              this.$refs.bpmn.setNodeError(_errorNodes)
              this.$message.error('请检查必填项')
              return
            }
            this.formData.xmlResource = xml
            this.formData.nodeInfo = JSON.stringify(cloneNodeInfo)
            this.formData.nodeCondition = JSON.stringify(this.condition)
            if (this.handleType === 'add' || this.handleType === 'copy') {
              flowCreate(this.formData).then(res => {
                if (res) {
                  this.$message.success('新增成功')
                  this.$router.push(window.prefix + '/bpmn/processDesign/list')
                  // sessionStorage.removeItem('processInfo')
                }
              })
            } else {
              this.formData.id = this.$route.query.id
              flowUpdate(this.formData).then(res => {
                if (res) {
                  this.$message.success('更新成功')
                  this.$router.push(window.prefix + '/bpmn/processDesign/list')
                  // sessionStorage.removeItem('processInfo')
                }
              })
            }
          })
        }
      })
    }
  },
  beforeRouteLeave(to, from, next) {
    to.meta.keepAlive = true
    next()
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0 20px;
  background: rgb(243, 245, 246) !important;
}
.tabs-header {
  display: flex;
  justify-content: space-between;
}
.bpmn {
  flex: 1;
}
::v-deep {
  .el-col {
    .el-select {
      width: 100%;
    }
  }
}

// 换肤样式修改
#app.dark-theme {
  .tabs-header {
    background: rgba(59, 139, 255, 0.4);
  }

  .containers.bpmn {
    background: rgba(59, 139, 255, 0.4);
    border: 1px solid rgba(59, 139, 255, 0.4);

    ::v-deep .property-panel {
      background: #1a448b;
      border-left: 1px solid rgba(59, 139, 255, 0.4);
    }
  }
}

</style>
